package xyz.lspace.newlrshk;

import android.app.Application;
import android.content.Context;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 改良输出方法, 暂时不输出到外部应用, 只输出到控制台
 */
public class Get17 implements IXposedHookLoadPackage {

    private static final String function = "sendChannelMessage";
    private static final String class_name =
            "com.zfyl.bobo.activity.room.AdminHomeActivity";
    private static final String SMSPACKAGENAME = "com.zfyl.bobo";


    //控制台输出log
    public void send(String str) {
        XposedBridge.log("xp输出信息:" + str);
    }

    //生成信息
    public void info(String className, String method, String info, boolean isAfter) {
        send(className + " , " + method + " (" + info + "), 执行" + (isAfter ? "前" : "后"));
    }

    public void sendMsg(String str) {

    }


    @Override
    public void handleLoadPackage(final LoadPackageParam lpparam) throws Throwable {
        send("xposed启动成功");
        if (lpparam.appInfo != null && lpparam.isFirstApplication

                && (SMSPACKAGENAME.equals(lpparam.packageName))) {


            // hook android.app.Application.attach method

            final Object[] applicationContext = new Object[2];
            XposedHelpers.findAndHookMethod(Application.class, "attach", Context.class, new XC_MethodHook() {

                @Override
                protected void beforeHookedMethod(MethodHookParam param) throws Throwable {

                    // this will be called before the clock was updated by the
                    // original method
                }

                @Override
                protected void afterHookedMethod(final MethodHookParam param) throws Throwable {
                    final String[] ip = {null};
                    final Context[] context = {null};
                    final Map<String, String> map = new HashMap<>();


                    //获取基础信息
/*
                    LHttp.post("http://ffkq.wenqujingdian.com/getIp?appName=bobo&userName" + LHttp.regName, new HashMap<String, String>(),new Callback() {
*/
                    LHttp.post("http://ffkq.wenqujingdian.com/getIp?appName=bobo&userName=" + LHttp.regName, new HashMap<String, String>(),new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
                            String string = response.body().string();
                            String result = DesBase64Util.decode("qwer8080", string);
                            send("base:" + result);
                            String[] param = result.split(",");
                            if (param[0].equals("1")) {
                                LHttp.reg = true;
                                LHttp.baseUrl = "http://" + param[1] + ":8889/";
                                send("url一装填: "+LHttp.baseUrl);
                                LHttp.sendMsg("模拟器已连接..");
                            }

                        }
                    });

                    final ClassLoader cl = ((Context) param.args[0]).getClassLoader();
                    Class<?> hookClass = getClass(cl, class_name);
                    final Class gifBeanDataBean = getClass(cl, "com.zfyl.bobo.bean.GifBean$DataBean");

                    /**
                     * hook类: com.c2vl.kgamebox.activity.c
                     * hook方法: X
                     * 方法参数: 无
                     * 方法作用: 返回当前房间的roomKey
                     */
                    XposedHelpers.findAndHookMethod(hookClass, function, String.class, new XC_MethodHook() {
                        @Override
                        protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
                            info(class_name, "sendChannelMessage", "发送消息", true);
                            String str = (String) param.args[0];
                            send("参数:" + str);
                            LHttp.sendServer(str);
                        }

                        @Override
                        protected void afterHookedMethod(MethodHookParam param) throws Throwable {

                        }
                    });
                    /**
                     * hook类: com.c2vl.kgamebox.activity.c
                     * hook方法: X
                     * 方法参数: 无
                     * 方法作用: 返回当前房间的roomKey
                     */
                    XposedHelpers.findAndHookMethod(getClass(cl, "com.zfyl.bobo.bean.GifBean"), "getData", new XC_MethodHook() {
                        @Override
                        protected void beforeHookedMethod(MethodHookParam param) throws Throwable {


                        }

                        @Override
                        protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                            List result = (List) param.getResult();
                            String getnum = LHttp.get("getNum");
                            if (getnum.contains(",")) {
                                send("getnum: " + getnum);
                                Object databean = result.get(0);
                                String[] split = getnum.split(",");
                                XposedHelpers.setObjectField(databean,"emoji",split[0]);
                                XposedHelpers.setObjectField(databean,"name",split[1]);
                                param.setResult(result);
                                send(result.get(0) + "");
                            }
                        }
                    });


                }//


                //获取类
                public Class getClass(ClassLoader classLoader, String className) {
                    Class hookClass = null;
                    try {
                        hookClass = classLoader.loadClass(className);
                        send("hookclass成功: " + hookClass.getName());
                    } catch (Exception e) {
                        send(e.getMessage());
                        send(e.getStackTrace().toString());
                        send("hookclass赋值失败 :" + className);
                    }
                    return hookClass;
                }
            }); // end of findAndHookMethod


        } // end of if
    } // end of handlePackage

}
